package com.shujia.kafka

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

object Demo4KafkaTran {
  def main(args: Array[String]): Unit = {

    /**
      *
      * 1、创建生产者
      */

    val properties = new Properties()

    //1、指定kafkabroker地址
    properties.setProperty("bootstrap.servers", "master:9092")

    //2、指定kv的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    properties.setProperty("transactional.id", "asdasd")
    //创建生产者
    val producer = new KafkaProducer[String, String](properties)

    //初始化事务
    producer.initTransactions()

    //开启事务
    producer.beginTransaction()

    val java = new ProducerRecord[String, String]("test_topic", "java")
    producer.send(java)
    println("第一条数据已发送")

    Thread.sleep(5000)

    val hadoop = new ProducerRecord[String, String]("test_topic", "hadoop")
    producer.send(hadoop)
    println("第二条数据已发送")
    //提交事务
    producer.commitTransaction()

    producer.close()

    /**
      *
      * --isolation-level read_committed  ： 读已提交的数据
      *
      * kafka-console-consumer.sh --bootstrap-server  master:9092  --from-beginning --isolation-level read_committed  --topic test_topic
      *
      */

  }

}
